import 'package:environmental_les_app/common/style/colours.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';

/// 附件选择组件
/// 功能：
/// - 点击“新增”选择手机存储文件（仅允许 PDF）
/// - 展示已选择文件的列表，支持删除
/// - 通过 [onChanged] 将当前已选文件列表回调给父组件
class AttachmentSelectWidget extends StatefulWidget {
  /// 当前初始文件列表（可为空）
  final List<PlatformFile>? initialFiles;

  /// 当已选文件列表变化时回调（返回 PlatformFile 列表）
  final ValueChanged<List<PlatformFile>>? onChanged;

  const AttachmentSelectWidget({
    super.key,
    this.initialFiles,
    this.onChanged,
  });

  @override
  State<AttachmentSelectWidget> createState() => _AttachmentSelectWidgetState();
}

class _AttachmentSelectWidgetState extends State<AttachmentSelectWidget> {
  late List<PlatformFile> _files;

  @override
  void initState() {
    super.initState();
    _files = widget.initialFiles != null ? List.from(widget.initialFiles!) : [];
  }

  Future<void> _pickFiles() async {
    // 只允许选择 pdf
    try {
      final result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['pdf'],
        allowMultiple: true,
        withData: false,
        withReadStream: false,
      );

      if (result == null) return;

      // 合并并去重（按 path 或 name）
      for (var f in result.files) {
        final exists = _files.any((e) => e.path == f.path || e.name == f.name);
        if (!exists) _files.add(f);
      }

      setState(() {});
      widget.onChanged?.call(List.unmodifiable(_files));
    } catch (e) {
      // 选择失败，简单地打印并不阻塞
      // 生产应考虑更友好的错误处理
      // ignore: avoid_print
      print('file pick error: $e');
    }
  }

  void _removeFile(int index) {
    _files.removeAt(index);
    setState(() {});
    widget.onChanged?.call(List.unmodifiable(_files));
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text(
              '附件',
              style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: Colours.text254),
            ),
            GestureDetector(
              onTap: _pickFiles,
              child: const Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.add, color: Colours.appMain, size: 18),
                  SizedBox(width: 4),
                  Text('新增',
                      style: TextStyle(color: Colours.appMain, fontSize: 14)),
                ],
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        ..._files.asMap().entries.map((entry) {
          final idx = entry.key;
          final f = entry.value;
          return Container(
            margin: const EdgeInsets.only(bottom: 8),
            decoration: BoxDecoration(
              color: Colors.grey.shade100,
              borderRadius: BorderRadius.circular(8),
            ),
            child: ListTile(
              leading: Container(
                width: 36,
                height: 36,
                decoration: BoxDecoration(
                  color: Colors.blue.shade50,
                  borderRadius: BorderRadius.circular(6),
                ),
                child: const Icon(Icons.picture_as_pdf, color: Colors.blue),
              ),
              title: Text(
                f.name,
                style: const TextStyle(fontSize: 14),
              ),
              trailing: GestureDetector(
                onTap: () => _removeFile(idx),
                child: Container(
                  width: 28,
                  height: 28,
                  decoration: BoxDecoration(
                    color: Colors.grey.shade600,
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(Icons.close, size: 18, color: Colors.white),
                ),
              ),
            ),
          );
        }),
        // 如果没有文件展示占位文字
        if (_files.isEmpty)
          Container(
            padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
            child: const Text(
              '未添加附件',
              style: TextStyle(color: Colors.grey, fontSize: 13),
            ),
          ),
      ],
    );
  }
}
